<?php
class App_Module_Admin_Component_Structure_Ctrl_Http extends Mozg_Controller_Instance
{
    public $_structMapper;

    public $_cid;
    public $_subCat;

    protected function ControllerInit()
    {
    	parent::ControllerInit();

        $this->_structMapper = Mozg_Mapper::Get('Structure');

        $this->_cid = intval(Mozg::Request('http')->get('cat'));
        if (!$this->_cid || !$this->_structMapper->GetOne(array('id' => $this->_cid)))
        {
        	if ($rootElem = $this->_structMapper->GetRoot()) $this->_cid = $rootElem->GetId();
        	else $this->_cid = 0;
        }

        $this->_subCat = intval(Mozg::Request('http')->get('subcat'));
        if ($this->_subCat && !$this->_structMapper->GetOne(array('id' => $this->_subCat)))
        {
        	$this->_subCat = 0;
        }
    }

    protected function GetExpandedElements()
    {
    	$list = explode('_', Mozg::Request('http')->getCookie('expanded_list'));

    	$session = Mozg_Mapper::Get('Session')->GetEntity('admin', 'structure');
    	$savedList = (array)$session->GetExpandedList();
    	if (in_array('-all', $list)) $savedList = array();
    	else if (in_array('all', $list)) $savedList = array_keys($this->_structMapper->GetList(array('parentId' => 0, 'levels' => 100)));

    	foreach ($list as $id)
    	{
    		$index = array_search(abs($id), $savedList);
    		if (($id < 0) && ($index !== false)) unset($savedList[$index]);
    		else if (($id > 0) && ($index === false)) $savedList[] = $id;
    	}

    	$session->SetExpandedList($savedList);
		Mozg_Mapper::Get('Session')->Save($session);

    	Mozg::Request('http')->SetCookie('expanded_list', null, null, Mozg_Router::Get('http')->Create(array('module' => 'admin', 'ctrl' => 'structure')));

    	return $savedList;
    }
}